/*
	Son las distintas habitaciones para trabajar con mapas.
		- Las habitaciones tienen lugares de trabajo.
		
*/
function Room(options) {
	
	this.SELECTED ="1";
	this.DRAG ="0.5";
	this.NOT_SELECTED = "0.3";

	if (! (this instanceof arguments.callee)) {
		return new arguments.callee(arguments);
	}

	this.sketches = [];
	this.overlays = [];
	this.subscriptions = [];
	this.client = options.client;
	this.name = options.name.toLowerCase();
	this.dom = options.dom;
	this.editable = (typeof options.editable == 'undefined') ?
		true : options.editable;
	this.persisted = (typeof options.persisted == 'undefined') ?
		true : options.editable;

	this.currentPosition = 
		{ lat: -33.457788
		, lng: -70.664105
		, zoom: 16
		}

	this.start();
}

Room.prototype.start = function() {
	var self = this;
	
	if (self.persisted) {
		// Subscribe to sketch updates.
		self.subscriptions.push(self.client.subscribe(self.roomPath('sketches'), function(sketch) {
			if (sketch.type == 'new')
				self.add(sketch);
			else if (sketch.type == 'delete')
				self.remove(sketch);

		}));
		self.subscriptions.push(self.client.subscribe(self.roomPath('moves'), function(data) {
			if (data.client != self.client.guid)
				self.moveTo(data.position)
		}));

		// Download previos sketches
		$.getJSON('/rooms/'+ this.name +'/sketches.json', function(data) {
			_.each(data.sketches, function(sketch) {
				self.add(sketch);
		  });
		})
	}
	
	// Display Map
	var mapDiv = document.createElement('div');
	mapDiv.className = "map";
	mapDiv.room = self;

	$(mapDiv).appendTo(self.dom);
	
	self.map = new Map({
		dom: mapDiv
		, controllable: false
		, position:
		{ lat: self.currentPosition.lat
		, lng: self.currentPosition.lng
		, zoom: self.currentPosition.zoom - 4
		}
	});
	
	/*
	 * Al parecer aca se encuentran todos los eventos
	 */
	
	
	self.map.onClick(function() {
		self.setActive(true);
	  });
	  
	
	
	YUI().use('dd-delegate','dd-drop-plugin', 'dd-constrain', 'dd-proxy', 'dd-scroll',function(Y) {
	 
		if(!self)
		   return;
		   
	
		var del = new Y.DD.Delegate({
			cont: '#personal',
			nodes: 'div.miniRoom',
			dragMode: 'intersect'
		});
	
		   //Listen for all drag:drag events
			del.on('drag:drag', function(e) {
			   
				Y.DD.DDM.syncActiveShims(true);
			});
	
		del.on('drag:start', function(e) {
			var drag = e.target;
			

//				
			var aux2=drag.get('node').cloneNode(true);
//				var aux3 =aux2.children;
//				var draggable = drag.get('dragNode');
//				//drag.set('dragNode',aux2);
//				document.getElementById('prueba2').innerHTML=aux2.get('innerHTML');
//                 
			drag.get('dragNode').set('innerHTML',aux2.get('innerHTML'));
//				drag.get('dragNode').set('childNodes',aux2.get('childNodes'));
//				drag.get('dragNode').set('children',aux2.get('children'));
//				
			 
			drag.get('dragNode').setAttribute('class', drag.get('node').getAttribute('class')); 
			drag.get('node').setStyle('z-index', '100');
			drag.get('node').setStyle('opacity', '.5');
			
			
			
			 
		});
		del.on('drag:end', function(e) {
		var node =e.target.get('node');
		 domNode =Y.Node.getDOMNode(node) ;
		var name = domNode.id;
			if(mapSketcherClient.currentRoomId == name)
				e.target.get('node').setStyle('opacity', '1');
			else	
				e.target.get('node').setStyle('opacity', '0.3');
		});
		
		del.on('drag:drag')
	 
		del.dd.plug(Y.Plugin.DDConstrained, {
			constrain2node: '#rooms'
		});
	 
		del.dd.plug(Y.Plugin.DDProxy, {
			moveOnEnd: false,
			cloneNode:false
		});
	 
		  del.dd.plug(Y.Plugin.DDNodeScroll, {
					node: '#personal'
				});
	 
		var element =  document.getElementById(self.map.dom);
		var drop = Y.one(self.map.dom).plug(Y.Plugin.Drop);
		drop.drop.on('drop:hit', function(e) {
			//drop.set('innerHTML', 'You dropped: <strong>' + e.drag.get('node').get('innerHTML') + '</strong>');
			/*var palabra="";
			for(x in e.drag.get('node')){
				palabra = palabra + x + "|";
			}
			*/
			var node = document.getElementById(e.drag.get('node').get('id'));
			self.copySketches(node.childNodes[0].room);
			e.target.get('node').setStyle('border-color', '#FFFF00');  
		});
		
		drop.drop.on('drop:over', function(e) {
			e.target.get('node').setStyle('border-color', '#00FF00');   
		});
		
		drop.drop.on('drop:exit', function(e) {
			e.target.get('node').setStyle('border-color', '#FFFF00');  
		});
	 
	});

}

Room.prototype.copySketches = function(room) {
	var self = this;
	_.each(room.sketches, function(sketch) {
		self.save(sketch);
	})
}

Room.prototype.roomPath = function(zone) {
	return '/room/' + this.name + '/' + zone;
}

Room.prototype.stop = function() {
	var self = this;

	_.each(self.subscriptions, function(s) {
		s.cancel();
	});
}
  
Room.prototype.save = function(sketch) {
	if(this.persisted) {
		this.client.sendSketch(this, sketch);
	} 
	else {
		this.add(sketch.to_json());
	}
}

Room.prototype.saveOverlay = function(overlay) {
	if(this.persisted) {
		//this.client.sendSketch(this, sketch);
		this.client.sendOverlay(this, overlay);
	} 
	else {
		//this.add(sketch.to_json());
		this.add(overlay.to_json());
	}
}

Room.prototype.destroy = function(sketch) {
	if(this.persisted) {
		this.client.removeSketch(this, sketch);
	} 
	else {
		this.remove(sketch.to_json());
	}
}

/*
Room.prototype.add = function(data) {
	var sketch = new Sketch(data);
	this.sketches.push(sketch);

	sketch.drawAt(this.map);
	if(this.workspace)
		this.workspace.addSketch(sketch);
}
*/
Room.prototype.add = function(data) {
	var overlay =  new Overlay(data);
	this.sketches.push(overlay);

	overlay.drawAt(this.map);
	if(this.workspace)
		this.workspace.addOverlay(overlay);
}

Room.prototype.remove = function(data) {
	var overlay = _.detect(this.overlays, function(s) { return s.id == data.id });
	if (overlay) {
		this.sketches = _.without(this.sketches, overlay);
		overlay.destroy();
	}
}

Room.prototype.setActive = function(active) {
	var self = this;


	if (active) {
		if ( self.client.activeRoom == self ) return;
		if ( self.client.activeRoom )
		  self.client.activeRoom.setActive(false);
		self.client.activeRoom = self;

		self.workspace = new Workspace(self);
		self.workspace.start();
		self.workspace.switchTo('panning');
		//self.dom.style.border = "3px solid red";
		self.dom.style.opacity =this.SELECTED;
		mapSketcherClient.currentRoomId=self.name;
		var parentNode = self.dom.parentNode;
		document.getElementById('personalDelete').style.display ="none";
		document.getElementById('collaborativeDelete').style.display ="none";
		document.getElementById('globalDelete').style.display ="none";
		if(parentNode.id =='personal')
			document.getElementById('personalDelete').style.display ="";
		else if(parentNode.id =='collaborative')
			document.getElementById('collaborativeDelete').style.display ="";
		else
			document.getElementById('globalDelete').style.display ="";
		
		
	} 
	else {
		self.workspace.stop();
		self.workspace = null;
		self.dom.style.border = "";
		self.dom.style.opacity =this.NOT_SELECTED;
	}
}

Room.prototype.moveTo = function(pos, options) {

	if( this.currentPosition == pos) return;

	this.currentPosition = pos;
	this.map.moveTo({
		lat: pos.lat
		, lng: pos.lng
		, zoom: pos.zoom - 4
	});

	if (options && options.userMove) {
		if (this.persisted) 
			this.client.sendMove(this, pos);
	} 
	else {
		if (this.workspace) 
			this.workspace.moveTo(pos);
	}

}
